package net.toocruel.iqismart.web.controller.admin;

import net.toocruel.iqismart.dao.condition.RoleCondition;
import net.toocruel.iqismart.entity.rbac.Resource;
import net.toocruel.iqismart.entity.rbac.Role;
import net.toocruel.iqismart.service.ResourceService;
import net.toocruel.iqismart.service.RoleService;
import net.toocruel.iqismart.service.exception.RoleRepeatException;
import net.toocruel.iqismart.service.exception.UserRepeatException;
import net.toocruel.iqismart.web.controller.base.AbstractBaseController;
import net.toocruel.iqismart.service.dto.SessionMessage;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

/**
 * @Description
 * @Auther sty
 * @createTime 2018/4/28 上午11:55
 */
@Controller
@RequestMapping("admin/role")
public class AdminRoleController extends AbstractBaseController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private ResourceService resourceService;

    @RequestMapping("")
    public String index(HttpServletRequest request,
                        HttpServletResponse response,
                        @RequestParam(defaultValue = "14") int size,
                        @RequestParam(defaultValue = "1") int page,
                        @RequestParam(defaultValue = "id") String sortBy,
                        @RequestParam(defaultValue = "asc") String sortOrder,
                        RoleCondition condition){

        Page<Role> roles = roleService.query(condition,new PageRequest(page-1, size,new Sort(Sort.Direction.fromString(sortOrder),sortBy)));
        request.setAttribute("roles",roles);
        request.setAttribute("condition",condition);
        request.setAttribute("page",page);
        request.setAttribute("size",size);
        return  "admin/role/index";
    }

    @GetMapping("create")
    public String create(HttpServletRequest request){
        return  "admin/role/create";
    }

    @PostMapping("create")
    public String doCreate(@Valid  Role role,BindingResult bindingResult,HttpServletRequest request) throws BindException {
        //此处 声明了BindingResult bindingResult参数 则验证失败时不会抛出4xx错误 需要自己处理
        if(!bindingResult.hasErrors()){
            try {
                roleService.create(role);
            return  "redirect:/admin/role";
            } catch (RoleRepeatException e) {
                e.printStackTrace();
                request.setAttribute("error",e);
            }
        }

        return  "admin/role/create";

    }

    @GetMapping("{id}")
    public String edit(@PathVariable("id") Long id, Role role,HttpServletRequest request,HttpSession session,RedirectAttributes redirectAttributes) {
        BeanUtils.copyProperties(roleService.findById(id),role);
        return  "/admin/role/edit";

    }

    @PutMapping("{id}")
    public String doEdit(@PathVariable("id") Long id,
                         @Valid  Role role,
                         BindingResult bindingResult,
                         HttpServletRequest request,
                         RedirectAttributes redirectAttributes
                         ) {
        if(!bindingResult.hasErrors()){
            try {
                roleService.update(role);
                redirectAttributes.addFlashAttribute("message",new SessionMessage("修改角色成功"));
                return  "redirect:/admin/role";
            } catch (UserRepeatException e) {
                e.printStackTrace();
                request.setAttribute("error",e);
            }
        }

        return  "redirect:/admin/role/"+id;

    }

    @PutMapping("resources/{id}")
    public String setResources(@PathVariable("id") Long id,
                         @Valid  Role role,
                         BindingResult bindingResult,
                         HttpServletRequest request,
                         RedirectAttributes redirectAttributes
    ) {
        if(!bindingResult.hasErrors()){
            try {
                roleService.setResources(role);
                redirectAttributes.addFlashAttribute("message",new SessionMessage("权限修改成功"));
                return  "redirect:/admin/role";
            } catch (UserRepeatException e) {
                e.printStackTrace();
                request.setAttribute("error",e);
            }
        }

        return  "redirect:/admin/role/"+id;

    }


    @PostMapping("destroy")
    public String doDestroy(Long[] id, HttpSession session,RedirectAttributes redirectAttributes) {
        int i = roleService.deleteMany(id);
        redirectAttributes.addFlashAttribute("message",new SessionMessage("成功删除了"+i+"个角色"));
        return  "redirect:/admin/role";

    }


    @ModelAttribute("allResource")
    public Resource createAllResource() {
        return resourceService.findByParent(null);
    }


}
